<template>
    <div class="productIn-index yuan-container">
        <a-card title="原料入库">
            <a-tabs type="card" :default-active-key="rawTypeKey" @change="tabChange">
                <a-tab-pane v-for="(item, i) in tabsData" :key="item.key" :tab="item.name"></a-tab-pane>
            </a-tabs>
            <div class="filter-panel">
                <a-input-search class="filter-list" allowClear v-model="keywords" placeholder="请输入品名/入库编号" @search="resetList" />
                <div class="filter-list">
                    <span>入库类型：</span>
                    <a-select allowClear style="width: 200px;color: #05b089;" v-model="enterType" placeholder="入库类型"
                        @change="resetList">
                        <a-select-option value="">全部</a-select-option>
                        <a-select-option :value="item.key" v-for="item in enterList"
                            :key="item.key">{{item.name}}</a-select-option>

                    </a-select>
                </div>
                <a-button type="primary" @click="add" class="filter-list" style="float: right;"
                    v-if="$utilCheckPermission(['rawEnterStorageAdd'])">新增</a-button>
            </div>
            <div class="table">
                <a-table bordered :rowKey="item=>item.id" :data-source="pageList" :columns="columnsShow" :pagination="pagination"
                    :loading="loading">
                    <template slot='action' slot-scope="text, record, index">
                        <div>
                            <a-button size="small"
                                v-if="record.state == 0 && record.enterStorageType == 'NSY' && $utilCheckPermission(['rawEnterStorageWriteInfo'])"
                                style="margin-right: 10px" :type="record.fillInDataState == 1 ? 'warning':'danger'" @click="editTraceability(record)">填写/编辑溯源信息</a-button>

                            <a-button size="small" v-if="(record.fillInDataState != 0 && record.state == 0) && $utilCheckPermission(['rawEnterStorageSubmitCheck'])"
                                style="margin-right: 10px" type="primary" @click="submitAudit(record)">提交审核</a-button>
                            <a-button size="small" v-if="(rawTypeKey == '辅料' && record.state == 0) && $utilCheckPermission(['rawEnterStorageSubmitCheck'])"
                                      style="margin-right: 10px" type="primary" @click="submitAudit(record)">提交审核</a-button>
                            <a-button size="small" style="margin-right: 10px" type="primary" @click="detail(record)"
                                v-if="$utilCheckPermission(['rawEnterStorageDetails'])">详情</a-button>

                            <a-button size="small" v-if="record.state == 1 && $utilCheckPermission(['rawEnterStorageCheck'])"
                                style="margin-right: 10px" type="primary" @click="passAudit(record)">审核</a-button>

                            <a-button size="small" v-if="record.state == 3 && $utilCheckPermission(['rawEnterStorageRejectReason'])"
                                style="margin-right: 10px" type="primary" @click="reason(record)">驳回理由</a-button>

                            <a-button size="small" v-if="record.state == 3 && $utilCheckPermission(['rawEnterStorageAnewEnterStorage'])"
                                style="margin-right: 10px" type="primary" @click="clickEdit">重新入库</a-button>

                            <a-popconfirm style="margin-right: 10px" v-if="record.state == 0 && $utilCheckPermission(['rawEnterStorageRemove'])" okText="确定"
                                cancelText="取消" title="确定删除吗？" @confirm="deleteRecord(record)">
                                <a-button size="small" type="primary">删除</a-button>
                            </a-popconfirm>
                            <a-button style="margin-right: 10px" size="small" v-if="record.state == 0 && $utilCheckPermission(['rawEnterStorageCompile'])"
                                      type="primary" @click="clickEdit(record)">修改</a-button>
                            <a-button v-if="record.state === 2" style="margin-top: 10px;margin-right: 10px" size="small" type="primary" @click="updateInputNum(record)">调整入库数量</a-button>
                        </div>
                    </template>
                </a-table>
            </div>
        </a-card>
        <AddVue :visible="addVisible" @closeModal="() => addVisible = false" :rawType="rawTypeKey" @resetList="getList"
            :editId="editId" />
        <EditTraceability :disabledForm="viewDetail" :editId="editTraceabilityId" :visible="editTraceabilityVisible"
            @closeModal="onClose"></EditTraceability>
        <Detail :disabledForm="true" :editId="detailId" :visible="detailVisible" @closeModal="detailClose"></Detail>
        <AccessoriesDetail :disabledForm="true" :editId="detailId" :visible="accessoriesDetailVisible" @closeModal="AccessoriesDetailClose"></AccessoriesDetail>
        <AccessoriesAudit :disabledForm="true" :auditId="passAuditId" :visible="AccessoriesAuditVisible" @closeModal="AccessoriesAuditClose" />
        <Audit :disabledForm="true" :edit-id="passAuditId" :visible="passAuditVisible" @closeModal="AuditOnClose" />
        <a-modal title="提交审核" :visible="auditVisible" @cancel="auditVisible=false" @ok="auditConfirm" okText="确定" cancelText="取消">
            <h2>是否提交审核？</h2>
        </a-modal>
        <a-modal title="驳回理由" :visible="reasonVisible" @cancel="reasonVisible=false" @ok="reasonConfirm" okText="确定"
            cancelText="取消">
            <a-textarea v-model="reasonText" placeholder="请输入驳回理由" :rows="4" />
        </a-modal>

        <a-modal :width="addInputModalOption.width" :visible="addInputModalOption.visible" :title="addInputModalOption.title" @ok="addInputModalOption.onOk" @cancel="addInputModalOption.onCancel"
                 :okText="addInputModalOption.okText" :cancelText="addInputModalOption.cancelText" class="yuan-modal testing-add-modal">
            <a-form-model ref="addInputForm" :model="addInputModalOption.formData" :rules="addInputModalOption.rules">
                <a-row :gutter="16" style="margin-bottom: 20px">
                    <a-col :span="8">
                        <span>当前品名:{{addInputModalOption.formData.varietyName}}</span>
                    </a-col>
                    <a-col :span="8">
                        <span>批号:{{addInputModalOption.formData.enterStorageBatch}}</span>
                    </a-col>
                    <a-col :span="8">
                        <span>当前入库数量:{{addInputModalOption.formData.leftNum}}{{addInputModalOption.formData.unit}}</span>
                    </a-col>
                </a-row>
                <a-form-model-item label="增加数量" prop="enterStorageNum">
                    <a-input-number style="width: 90%" v-model="addInputModalOption.formData.enterStorageNum"/> {{addInputModalOption.formData.unit}}
                </a-form-model-item>
                <a-form-model-item label="调整时间" prop="storageTime">
                    <a-date-picker :locale="locale" valueFormat="YYYY-MM-DD" style="width: 90%" v-model="addInputModalOption.formData.storageTime" />
                </a-form-model-item>
                <a-row :gutter="16" style="margin-bottom: 20px">
                    <a-col :span="24">
                        <span>调整人员:{{curOperatorName}}</span>
                    </a-col>
                </a-row>
            </a-form-model>
        </a-modal>
    </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { h } from "vue";
import nextApi, { EnterLibraryListRes } from "@/api/nextApi";
import AddVue from "./components/Add.vue";
import EditTraceability from "./components/editTraceability.vue";
import Audit from "@/views/appViews/rowMaterialIncoming/components/audit.vue";
import Detail from "./components/DetailInfo.vue";
import AccessoriesDetail from "@/views/appViews/rowMaterialIncoming/components/AccessoriesDetail.vue";
import AccessoriesAudit from "@/views/appViews/rowMaterialIncoming/components/AccessoriesAudit.vue";
import locale from "ant-design-vue/es/date-picker/locale/zh_CN";

@Component({
    name: "productInMgtIndex",
    components: {AccessoriesAudit, AddVue, EditTraceability, Audit, Detail,AccessoriesDetail },
})
export default class extends Vue {
    locale: any = locale;

    addInputModalOption = {
        visible:false,
        loading:false,
        title:'调整入库数量',
        width:600,
        okText:'确定',
        cancelText:'取消',
        formData:{
            enterStorageBatch:'',
            varietyName:'',
            id:'',
            leftNum:'',
            enterStorageNum:null,
            unit:'',
            storageTime:null,
        },
        rules:{
            enterStorageNum:[
                {required:true,message:'请输入调整入库数量',trigger:'blur'}
            ]
        },
        onOk:()=>{
            this.addInputOk()
        },
        onCancel:()=>{
            this.addInputModalOption.visible = false
        }

    }

    tabsData = [
        { key: "中药材", name: "中药材" },
        { key: "辅料", name: "辅料" },
    ];
    pagination = {
        pageSize: 10,
        current: 1,
        total: 0,
        showTotal: (total: number) => `共${total}条`,
        onChange: this.pageChange,
    };
    columns = [
        {
            title: "序号",
            dataIndex: "index",
            key: "index",
            align: "center",
            customRender: (text: any, record: any, index: any) => `${index + 1}`,
        },
        {
            align: "center",
            dataIndex: "varietyName",
            key: "varietyName",
            title: "品名",
        },
        {
            align: "center",
            dataIndex: "enterStorageType",
            key: "enterStorageType",
            title: "入库类型",
            customRender: (text: any, record: any, index: any) => {
                return this.enterList.find((item) => item.key === record.enterStorageType)?.name || "--";
            },
        },
        {
            align: "center",
            dataIndex: "enterStorageBatch",
            key: "enterStorageBatch",
            title: "入库批号",
        },
        {
            align: "center",
            dataIndex: "enterStorageNum",
            key: "enterStorageNum",
            title: "入库数量",
            customRender: (text: any, record: any) => `${record.enterStorageNum}${record.unit}`,
        },
        {
            align: "center",
            dataIndex: "realTimeNum",
            key: "realTimeNum",
            title: "剩余数量",
            customRender: (text: any, record: any) => `${record.realTimeNum}${record.unit}`,
        },
        {
            align: "center",
            dataIndex: "massStandard",
            key: "massStandard",
            title: "质量标准",
        },

        {
            align: "center",
            dataIndex: "state",
            key: "state",
            title: "状态",
            customRender: (text: any) => {
                return text == 0 ? "待入库" : text == 1 ? "待审核" : text == 2 ? "已入库" : "已驳回";
            },
        },
        {
            align: "center",
            dataIndex: "operator",
            key: "operator",
            title: "操作人",
        },
        {
            align: "center",
            dataIndex: "enterStorageTime",
            key: "enterStorageTime",
            title: "入库时间",
        },
        {
            align: "center",
            dataIndex: "action",
            key: "action",
            title: "操作",
            width:420,
            scopedSlots: { customRender: "action" },
        },
    ];
    loading = false;
    pageList: EnterLibraryListRes[] = [];
    keywords = "";
    enterType = "";
    rawTypeKey = "中药材";
    enterList = [
        { key: "SY", name: "溯源入库" },
        { key: "NSY", name: "非溯源入库" },
        { key: "CG", name: "采购入库" },
    ];
    addInputOk(){
        (this.$refs.addInputForm as any).validate(async (valid: boolean) => {
            if(valid){
                try{
                    this.addInputModalOption.loading = true
                    const res = await nextApi.updatePutInNum(this.addInputModalOption.formData)
                    this.$message.success(res.msg)
                    await this.getList()
                }finally {
                    this.addInputModalOption.loading = false
                    await this.getList()
                    this.addInputModalOption.visible = false
                }
            }
        })
    }
    async getList() {
        this.pageList = [];
        try {
            this.loading = true;
            const res = await nextApi.getRawInboundList({
                pageSize: this.pagination.pageSize,
                pageNum: this.pagination.current,
                varietyName: this.keywords,
                rawType: this.rawTypeKey,
                enterStorageType: this.enterType,
            });
            this.pagination.total = res.data?.total || 0;
            this.pageList = res.data?.rows || [];
        } finally {
            this.loading = false;
        }
    }
    resetList() {
        this.pagination.current = 1;
        this.getList();
    }
    columnsShow: any[] = [];
    tabChange(e: string) {
        this.columnsShow = [...this.columns];
        this.rawTypeKey = e;
        if (this.rawTypeKey === "中药材") {
            this.columnsShow.splice(6, 0, {
                align: "center",
                dataIndex: "source",
                key: "source",
                title: "供应商",
            });
        }

        this.resetList();
    }
    pageChange(page: number, pageSize: number) {
        this.pagination.pageSize = pageSize;
        this.pagination.current = page;
        this.getList();
    }
    async mounted() {
        this.tabChange(this.rawTypeKey);
        this.getList();
    }
    addVisible = false;
    editId = "";
    add() {
        this.editId = "";
        this.addVisible = true;
    }
    clickEdit(item: EnterLibraryListRes) {
        this.editId = item.id;
        this.addVisible = true;
    }
    updateInputNum(record: any){
        this.addInputModalOption.visible = true
        this.addInputModalOption.formData.id = record.id
        this.addInputModalOption.formData.leftNum = record.realTimeNum
        this.addInputModalOption.formData.unit = record.unit
        this.addInputModalOption.formData.varietyName = record.varietyName
        this.addInputModalOption.formData.enterStorageBatch = record.enterStorageBatch
    }
    //溯源信息弹窗
    editTraceabilityVisible = false;
    editTraceabilityId = "";
    viewDetail = false;
    editTraceability(record: any) {
        this.editTraceabilityVisible = true;
        this.editTraceabilityId = record.id;
    }
    onClose() {
        this.editTraceabilityVisible = false;
        this.viewDetail = false;
        this.getList();
    }
    detailVisible = false;
    //辅料详情窗口开关
    accessoriesDetailVisible = false
    detailId = "";
    detail(record: EnterLibraryListRes) {
        if(this.rawTypeKey == '中药材'){
            this.detailVisible = true;
            this.detailId = record.id;
        }else{
            this.accessoriesDetailVisible = true
            this.detailId = record.id;
        }
    }
    detailClose() {
        this.detailVisible = false;
        this.getList();
    }
    AccessoriesDetailClose(){
        this.accessoriesDetailVisible = false
        this.getList()
    }
    //提交审核
    auditVisible = false;
    auditId = "";
    submitAudit(record: EnterLibraryListRes) {
        this.auditVisible = true;
        this.auditId = record.id;
    }
    async auditConfirm() {
        let params = {
            id: this.auditId,
            state: 1,
        };
        const res = await nextApi.auditState(params);
        if (res.code == 200) {
            this.$message.success(res.msg);
            this.auditVisible = false;
            this.getList();
        } else {
            this.$message.error(res.msg);
        }
    }
    async deleteRecord(record: EnterLibraryListRes) {
        const res = await nextApi.deleteInboundInfo(record.id);
        if (res.code == 200) {
            this.$message.success(res.msg);
            this.getList();
        } else {
            this.$message.error(res.msg);
        }
    }
    //审核
    passAuditVisible = false;
    passAuditId = "";
    AccessoriesAuditVisible = false
    passAudit(record: EnterLibraryListRes) {
        if(this.rawTypeKey == '中药材'){
            this.passAuditVisible = true;
            this.passAuditId = record.id;
            console.log('中药材-审核',record)
        }else{
            this.AccessoriesAuditVisible = true
            this.passAuditId = record.id;
            console.log('辅料-审核',record)
        }

    }
    AuditOnClose() {
        this.passAuditVisible = false;
        this.getList();
    }
    AccessoriesAuditClose(){
        this.AccessoriesAuditVisible = false
        this.getList()
    }
    reasonVisible = false;
    reasonId = "";
    reasonText = "";
    reason(record: EnterLibraryListRes) {
        this.reasonVisible = true;
        this.reasonId = record.id;
    }
    async reasonConfirm() {
        if (!this.reasonText) {
            this.$message.error("请输入驳回理由");
            return;
        }
        let params = {
            id: this.reasonId,
            state: 3,
            reason: this.reasonText,
        };
        const res = await nextApi.auditState(params);
        if (res.code == 200) {
            this.$message.success(res.msg);
            this.reasonVisible = false;
            this.getList();
        } else {
            this.$message.error(res.msg);
        }
    }
    hideSource() {
        console.info(123);
        if (this.rawTypeKey === "辅料") return 0;
        return 1;
    }
    get curOperatorName(){
        let user = localStorage.getItem('siteUserInfo')
        if(user){
            let userInfo = JSON.parse(user)
            return userInfo.name
        }
    }
}
</script>
<style lang="scss">
.productIn-index {
    padding: 20px;
}
</style>
